/**
 * OpenAL cross platform audio library
 * Copyright (C) 2010 by Chris Robinson
 * This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the
 *  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 *  Boston, MA  02111-1307, USA.
 * Or go to http://www.gnu.org/copyleft/lgpl.html
 */

#include "config.h"

#include <stdlib.h>

#include "alMain.h"
#include "AL/al.h"
#include "AL/alc.h"

#include "qThreadWrapper.h"
#include "qAudioOutputWrapper.h"

static const ALCchar qt_device[] = "Qt Default";

typedef struct
{
    Thread thread;
    AudioOutput audio;
    AudioBuffer buffer;
    volatile int running;
} QtData;

#ifdef _SYMBIAN
static void* tick_function(void* arg)
{
    ALCdevice* device = (ALCdevice*)arg;
    QtData* data = (QtData*)device->ExtraData;

    if (!data->running)
    {
        return NULL;
    }

    if (!isAudioOutputReady(data->audio))
    {
        return NULL;
    }

    int bufferSizeInBytes = getAudioBufferPeriodSize(data->audio);
    int bufferSizeInSamples = bufferSizeInBytes / aluFrameSizeFromFormat(device->Format);

    char* buffer = (char*)calloc(bufferSizeInBytes, sizeof(char));

    int bytesFree = getAudioBufferFreeSize(data->audio);
    int chunks = bytesFree / bufferSizeInBytes;

    while (chunks)
    {
        aluMixData(device, buffer, bufferSizeInSamples);
        writeAudioBuffer(data->buffer, buffer, bufferSizeInBytes);
        --chunks;
    }

    free(buffer);

    return NULL;
}
#else
static void* thread_function(void* arg)
{
    ALCdevice* device = (ALCdevice*)arg;
    QtData* data = (QtData*)device->ExtraData;

    while (!isAudioOutputReady(data->audio))
    {
    }

    AL_PRINT("QAudioOutput ready.");

    int bufferSizeInBytes = getAudioBufferPeriodSize(data->audio);
    int bufferSizeInSamples = bufferSizeInBytes / aluFrameSizeFromFormat(device->Format);

    char* buffer = (char*)calloc(bufferSizeInBytes, sizeof(char));

    while (data->running)
    {
        int bytesFree = getAudioBufferFreeSize(data->audio);
        int chunks = bytesFree / bufferSizeInBytes;

        while (chunks)
        {
            aluMixData(device, buffer, bufferSizeInSamples);
            writeAudioBuffer(data->buffer, buffer, bufferSizeInBytes);
            --chunks;
        }

        sleepThread(data->thread, 500);
    }

    free(buffer);

    return NULL;
}
#endif

static ALCboolean qt_open_playback(ALCdevice *device, const ALCchar *deviceName)
{
    QtData* data;

    if (!deviceName)
    {
        deviceName = qt_device;
    }
    else if (strcmp(deviceName, qt_device) != 0)
    {
        return ALC_FALSE;
    }

    data = (QtData*)calloc(1, sizeof(*data));
    device->szDeviceName = strdup(deviceName);
    device->ExtraData = data;
    return ALC_TRUE;
}

static void qt_close_playback(ALCdevice *device)
{
    QtData* data = (QtData*)device->ExtraData;

    if (data != NULL)
    {
        free(data);
        device->ExtraData = NULL;
    }
}

static ALCboolean qt_reset_playback(ALCdevice *device)
{
    QtData* data = (QtData*)device->ExtraData;

    if (aluChannelsFromFormat(device->Format) >= 2)
    {
        device->Format = aluBytesFromFormat(device->Format) >= 2 ? AL_FORMAT_STEREO16 : AL_FORMAT_STEREO8;
    }
    else
    {
        device->Format = aluBytesFromFormat(device->Format) >= 2 ? AL_FORMAT_MONO16 : AL_FORMAT_MONO8;
    }

    SetDefaultChannelOrder(device);

    int frequency = device->Frequency;
    int channels = aluChannelsFromFormat(device->Format);
    int sampleSize = aluBytesFromFormat(device->Format) == 1 ? 8 : 16;

    AudioOutput audioOutput = createAudioOutput(frequency, channels, sampleSize);

    if (!audioOutput)
    {
        AL_PRINT("Failed to create AudioOutput!");
        return ALC_FALSE;
    }

    AudioBuffer audioBuffer = startAudioOutput(audioOutput);

    if (!audioBuffer)
    {
        AL_PRINT("Failed to start AudioOutput!");
        return ALC_FALSE;
    }

    data->audio = audioOutput;
    data->buffer = audioBuffer;
#ifdef _SYMBIAN
    data->thread = createThread(tick_function, device);
#else
    data->thread = createThread(thread_function, device);
#endif
    data->running = 1;

    return ALC_TRUE;
}

static void qt_stop_playback(ALCdevice *device)
{
    QtData* data = (QtData*)device->ExtraData;

    if (data->running)
    {
        data->running = 0;
        destroyThread(data->thread);
    }

    stopAudioOutput(data->audio);
    destroyAudioOutput(data->audio);
}

static ALCboolean qt_open_capture(ALCdevice *pDevice, const ALCchar *deviceName)
{
    (void)pDevice;
    (void)deviceName;
    return ALC_FALSE;
}

static void qt_close_capture(ALCdevice *pDevice)
{
    (void)pDevice;
}

static void qt_start_capture(ALCdevice *pDevice)
{
    (void)pDevice;
}

static void qt_stop_capture(ALCdevice *pDevice)
{
    (void)pDevice;
}

static void qt_capture_samples(ALCdevice *pDevice, ALCvoid *pBuffer, ALCuint lSamples)
{
    (void)pDevice;
    (void)pBuffer;
    (void)lSamples;
}

static ALCuint qt_available_samples(ALCdevice *pDevice)
{
    (void)pDevice;
    return 0;
}

static const BackendFuncs qt_funcs = {
    qt_open_playback,
    qt_close_playback,
    qt_reset_playback,
    qt_stop_playback,
    qt_open_capture,
    qt_close_capture,
    qt_start_capture,
    qt_stop_capture,
    qt_capture_samples,
    qt_available_samples
};

void alc_qt_init(BackendFuncs *func_list)
{
    *func_list = qt_funcs;
}

void alc_qt_deinit(void)
{
}

void alc_qt_probe(int type)
{
    if (type == DEVICE_PROBE)
    {
        AppendDeviceList(qt_device);
    }
    else if (type == ALL_DEVICE_PROBE)
    {
        AppendAllDeviceList(qt_device);
    }
}
